package com.simple.relaxed.anno.impl;

import com.simple.relaxed.anno.PartLayout;
import com.simple.relaxed.local.LocalLayout;
import com.simple.relaxed.manager.impl.LocalLayoutManager;
import ohos.agp.components.Component;
import ohos.app.Context;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class PartLayoutImpl {

    /**
     * 被@PartLayout注解标记的Field将会注入指定的LocalLayout对象。被指定的Field对象，需要是Component对象1，否则将会因为类型不兼容，导致程序奔溃
     *
     * @param context 上下文对象，必要参数，后续LocalLayout对象需求
     */
    public static void partLayoutImpl(Context context) {
        Class<?> aClass = context.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            PartLayout partLayout = field.getDeclaredAnnotation(PartLayout.class);
            if (partLayout == null) {
                continue;
            }
            Class<? extends LocalLayout> clazz = partLayout.clazz();
            field.setAccessible(true);
            try {
                Component component = LocalLayoutManager.getInstance().getComponent(clazz, context);
                if (component == null) {
                    continue;
                }
                field.set(context, component);
            } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
